<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useQuestionStore } from '@/stores/question'
import { Search, Bell } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

dayjs.extend(relativeTime)

const router = useRouter()
const userStore = useUserStore()
const questionStore = useQuestionStore()

const searchQuery = ref('')
const askDialogVisible = ref(false)
const notifications = ref([])
const hotTopics = ref([
  { id: 1, name: '科技' },
  { id: 2, name: '互联网' },
  { id: 3, name: '生活' }
])

const questionForm = ref({
  title: '',
  content: '',
  topics: []
})

const isLoggedIn = computed(() => userStore.isLoggedIn)
const userAvatar = computed(() => userStore.getUserInfo?.avatar || '')
const hasNotification = computed(() => notifications.value.some(n => !n.read))

const handleSearch = () => {
  if (!searchQuery.value.trim()) return
  router.push({
    path: '/search',
    query: { q: searchQuery.value }
  })
}

const showAskDialog = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  askDialogVisible.value = true
}

const handleSubmitQuestion = async () => {
  try {
    const success = await questionStore.submitQuestion(questionForm.value)
    if (success) {
      ElMessage.success('问题发布成功')
      askDialogVisible.value = false
      questionForm.value = {
        title: '',
        content: '',
        topics: []
      }
      router.push('/question/' + success.id)
    }
  } catch (error) {
    console.error('Failed to submit question:', error)
    ElMessage.error('发布失败')
  }
}

const handleLogout = async () => {
  try {
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/')
  } catch (error) {
    console.error('Logout failed:', error)
    ElMessage.error('退出失败')
  }
}

const formatTime = (time) => {
  return dayjs(time).fromNow()
}
</script>

<template>
  <el-config-provider :locale="zhCn">
    <div class="app">
      <el-container>
        <el-header height="60px">
          <div class="header-content">
            <div class="left">
              <router-link to="/" class="logo">
                编乎
              </router-link>
              <el-menu
                mode="horizontal"
                :router="true"
                class="main-menu"
              >
                <el-menu-item index="/">首页</el-menu-item>
                <el-menu-item index="/hot">热榜</el-menu-item>
                <el-menu-item index="/topics">话题</el-menu-item>
              </el-menu>
            </div>
            
            <div class="center">
              <el-input
                v-model="searchQuery"
                placeholder="搜索你感兴趣的内容..."
                class="search-input"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <div class="right">
              <template v-if="isLoggedIn">
                <el-button type="primary" @click="showAskDialog">
                  提问
                </el-button>
                <el-popover
                  placement="bottom-end"
                  :width="300"
                  trigger="click"
                >
                  <template #reference>
                    <el-badge :is-dot="hasNotification">
                      <el-button>
                        <el-icon><Bell /></el-icon>
                      </el-button>
                    </el-badge>
                  </template>
                  <div class="notification-panel">
                    <div class="notification-header">
                      <span>消息通知</span>
                      <el-button type="text">全部标记为已读</el-button>
                    </div>
                    <div v-if="notifications.length" class="notification-list">
                      <div
                        v-for="notification in notifications"
                        :key="notification.id"
                        class="notification-item"
                      >
                        <el-avatar :size="40" :src="notification.sender.avatar" />
                        <div class="notification-content">
                          <div class="notification-text">
                            {{ notification.content }}
                          </div>
                          <div class="notification-time">
                            {{ formatTime(notification.time) }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <el-empty v-else description="暂无消息" />
                  </div>
                </el-popover>
                
                <el-dropdown trigger="click">
                  <el-avatar :size="40" :src="userAvatar" />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <router-link to="/profile">我的主页</router-link>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <router-link to="/settings">设置</router-link>
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="handleLogout">
                        退出登录
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
              <template v-else>
                <router-link to="/login">
                  <el-button>登录</el-button>
                </router-link>
                <router-link to="/register">
                  <el-button type="primary">注册</el-button>
                </router-link>
              </template>
            </div>
          </div>
        </el-header>
        
        <el-main>
          <div class="main-content">
            <router-view v-slot="{ Component }">
              <transition name="fade" mode="out-in">
                <component :is="Component" />
              </transition>
              <el-footer height="100px" width="100%">
              <div class="footer-content">
                <div class="footer-links">
                  <a href="#">关于我们</a>
                  <a href="#">使用条款</a>
                  <a href="#">隐私政策</a>
                  <a href="#">帮助中心</a>
                  <a href="#">联系我们</a>
                </div>
              <div class="copyright">
              © 2025 能工. All rights reserved.
            </div>
          </div>
        </el-footer>
            </router-view>
          </div>
        </el-main>
        
      </el-container>
    </div>

    <!-- 提问对话框 -->
    <el-dialog
      v-model="askDialogVisible"
      title="写下你的问题"
      width="60%"
    >
      <el-form :model="questionForm" label-position="top">
        <el-form-item
          label="问题标题"
          :rules="[
            { required: true, message: '请输入问题标题', trigger: 'blur' },
            { min: 5, message: '标题不能少于5个字符', trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="questionForm.title"
            placeholder="请用一句话说明你的问题"
          />
        </el-form-item>
        
        <el-form-item
          label="问题描述（可选）"
        >
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="4"
            placeholder="添加问题背景、条件等详细信息"
          />
        </el-form-item>
        
        <el-form-item label="话题">
          <el-select
            v-model="questionForm.topics"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="选择或创建话题"
          >
            <el-option
              v-for="topic in hotTopics"
              :key="topic.id"
              :label="topic.name"
              :value="topic.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="askDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitQuestion">
            发布问题
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-config-provider>
</template>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  min-height: 100vh;
}

#app {
  height: 100vh;
  margin: 0;
  padding: 0;
}
</style>

<style scoped lang="scss">
.app {
  min-height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;
  
  .el-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    width: 100%;
    margin: 0;
    padding: 0;
  }
  
  .el-header {
    background-color: #fff;
    box-shadow: 0 1px 3px rgba(18, 18, 18, 0.1);
    width: 100%;
    left: 0;
    z-index: 100;
    
    .header-content {
      width: 90%;
      max-width: 1000px;
      margin: 0 auto;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      
      .left {
        display: flex;
        align-items: center;
        flex-shrink: 0;

        .logo {
          font-size: 24px;
          font-weight: bold;
          color: #0066ff;
          text-decoration: none;
          margin-right: 40px;
        }
        
        .main-menu {
          border-bottom: none;
        }
      }
      
      .center {
        flex: 1;
        max-width: 500px;
        margin: 0 40px;
        
        .search-input {
          .el-input__wrapper {
            border-radius: 20px;
          }
        }
      }
      
      .right {
        display: flex;
        align-items: center;
        gap: 15px;
        flex-shrink: 0;
      }
    }
  }
  
  .el-main {
    flex: 1;
    width: 100%;
    
    .main-content {
      width: 90%;
      max-width: 1000px;
      margin: 0 auto;
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }
  
  .el-footer {
    background-color: #fff;
    width: 100%;
    left: 0;
    
    .footer-content {
      width: 90%;
      max-width: 1000px;
      margin: 0 auto;
      padding: 20px 0;
      text-align: center;
      box-sizing: border-box;
      
      .footer-links {
        margin-bottom: 15px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 15px;
        
        a {
          color: #8590a6;
          text-decoration: none;
          font-size: 14px;
          &:hover {
            color: #175199;
          }
        }
      }
      
      .copyright {
        color: #8590a6;
        font-size: 14px;
      }
    }
  }
}

.notification-panel {
  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .notification-list {
    max-height: 400px;
    overflow-y: auto;
    
    .notification-item {
      display: flex;
      padding: 10px;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .notification-content {
        margin-left: 10px;
        flex: 1;
        
        .notification-text {
          font-size: 14px;
          margin-bottom: 5px;
        }
        
        .notification-time {
          font-size: 12px;
          color: #8590a6;
        }
      }
    }
  }
}

// 路由过渡动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
